#include "ts.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <memory.h>

void ts_parse(unsigned char *buf, ts_t *ts)
{
    int i_skip = 0, adap_len = 0, okIDR = 0, okSPS = 0, okPPS = 0;
    int tmp8;
    long tmp16;
    memset(ts, 0, sizeof(ts_t));
    pes_t *pes = &(ts->pes);
    ts->sync_byte = 0x47;
    ts->tei = ((buf[1] & 0x80) >> 7);
    ts->pusi = ((buf[1] & 0x40) >> 6);
    ts->tp = ((buf[1] & 0x20) >> 5);
    ts->PID = ((buf[1] & 0x1f) << 4) + buf[2];
    ts->tsc = ((buf[3] & 0xC0) >> 6);
    ts->afc = ((buf[3] & 0x30) >> 4);
    ts->cc = (buf[3] & 0x0f);
    if (ts->afc&0x10) {
        adap_len = buf[i_skip];
        i_skip += adap_len;
    }
    if (ts->pusi)
        i_skip = 4;
    else 
        i_skip = 0;
    if ((ts->afc&0x01) && (ts->pusi)) {
#if 0
        if (ts->payload_unit_start_indicator) {
            i_skip++;
        }
#endif
        i_skip += 3;
        if (buf[i_skip] == 1)
            i_skip++;
        pes->stream_id = buf[i_skip++];
        pes->PESplen = (buf[i_skip] << 4) + buf[i_skip+1];
        i_skip += 3;
        tmp8 = buf[i_skip++];
        pes->PDflags = ((tmp8 & 0xC0) >> 6);
        pes->PEShlen = buf[i_skip++];
        if (pes->PDflags == 2) {
            tmp8 = buf[i_skip++];
            pes->pts = (((tmp8 & 0x0E) >> 1) << 30);
            tmp16 = (buf[i_skip] << 8) + buf[i_skip+1];
            i_skip += 2;
            pes->pts += (((tmp16 & 0xFFFE) >> 1) << 15);
            tmp16 = (buf[i_skip] << 8) + buf[i_skip+1];
            i_skip += 2;
            pes->pts += ((tmp16 & 0xFFFE) >> 1);
        }
        if (pes->PDflags == 3) {
            tmp8 = buf[i_skip++];
            pes->pts = (((tmp8 & 0x0E) >> 1) << 30);
            tmp16 = (buf[i_skip] << 8) + buf[i_skip+1];
            i_skip += 2;
            pes->pts += (((tmp16 & 0xFFFE) >> 1) << 15);
            tmp16 = (buf[i_skip] << 8) + buf[i_skip+1];
            i_skip += 2;
            pes->pts += ((tmp16 & 0xFFFE) >> 1);
//
            tmp8 = buf[i_skip++];
            pes->dts = (((tmp8 & 0x0E) >> 1) << 30);
            tmp16 = (buf[i_skip] << 8) + buf[i_skip+1];
            i_skip += 2;
            pes->dts += (((tmp16 & 0xFFFE) >> 1) << 15);
            tmp16 = (buf[i_skip] << 8) + buf[i_skip+1];
            i_skip += 2;
            pes->dts += ((tmp16 & 0xFFFE) >> 1);
        }
    }
    for (int i = i_skip; i < 188 - 4; i++) {
        if (!buf[i] && !buf[i+1] && !buf[i+2] && (buf[i+3] == 1)) {
            if ((buf[i+4]&0x1f) == 5)
                ts->IDR = true;
            if ((buf[i+4]&0x1f) == 7)
                ts->SPS = true;
            if ((buf[i+4]&0x1f) == 8)
                ts->PPS = true;
        }
    }
    return;
}
